package cn.tedu.mall.producer.service.impl;

import cn.tedu.mall.producer.ex.ServiceException;
import cn.tedu.mall.producer.mapper.AlbumMapper;
import cn.tedu.mall.producer.pojo.dto.AlbumAddNewDTO;

import cn.tedu.mall.producer.pojo.entity.Album;
import cn.tedu.mall.producer.pojo.vo.AlbumListItemVO;
import cn.tedu.mall.producer.service.IAlbumService;

import cn.tedu.mall.producer.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;


@Slf4j
@Service
public class AlbumServiceImpl implements IAlbumService {
    @Autowired
    private AlbumMapper albumMapper;


    @Override
    public void addNew(AlbumAddNewDTO albumAddNewDTO) {
        Album album = new Album();
        String name = albumAddNewDTO.getName();
        int i = albumMapper.countByName(name);
        if (i>0){
            String message = "添加相册失败，相册名称【" + name + "】已经被占用！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        BeanUtils.copyProperties(albumAddNewDTO,album);
        int insert = albumMapper.insert(album);
        if (album.getSort() == null) {
            album.setSort(0);
        }

        if (insert!=1){
            String message = "添加相册失败，服务器忙，请稍后再次尝试！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

    }

    @Override
    public void deleteById(Long id) {
        Album album = albumMapper.selectById(id);
        if(album==null){
            String message = "删除相册失败，尝试删除的数据不存在！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        int count = albumMapper.deleteById(id);
        if (count!=1){
            String message = "删除相册失败，服务器忙，请稍后再次尝试！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
    }

    @Override
    public List<AlbumListItemVO> list() {
        return albumMapper.list();
    }
}
